<?php

namespace app\common\model;

class Client extends Common
{
    protected $insert = ['addtime' => SYS_TIME];
    protected $update = ['typeid'];
    protected $append = ['kindname', 'statusname'];

    protected function getAddtimeAttr($value)
    {
        return date("Y-m-d H:i", $value);
    }

    //0:未处理，1：跟进中，2：成交，3：失败，4：信息错误
    protected function getStatusnameAttr($value, $data)
    {
        if (isset($data['status'])) {
            return config('CLIENT_STATUS.' . $data['status']);
        } else {
            return '';
        }
    }

    protected function getKindnameAttr($value, $data)
    {
        return isset($data['kind']) ? config('CLIENT_KIND.' . $data['kind']) : '';
    }

    protected function getRealnameAttr($value, $data)
    {
        return model('AdminUser')->where('userid', $data['brokerid'])->value('realname');
    }

    protected function getDirectornameAttr($value, $data)
    {
        return model('AdminUser')->where('userid', $data['userid'])->value('realname');
    }

    protected function getUinfoAttr($value, $data)
    {
        return model('AdminUser')->where('userid', $data['brokerid'])->field('realname, phone, username, avatar')->find();
    }

    protected function getAlldataAttr($value, $data)
    {
        // $data['realname'] = model('AdminUser')->where('userid', $data['brokerid'])->value('realname');
        $data['directorname'] = model('AdminUser')->where('userid', $data['userid'])->value('realname');
        $data['sourcename'] = $data['source'] ? config('CLIENT_SOURCE.' . $data['source']) : '未设置';
        $data['skilledname'] = $data['skilled'] ? config('CLIENT_SKILLED.' . $data['skilled']) : '未设置';
        $data['statusname'] = $data['status'] ? config('CLIENT_STATUS.' . $data['status']) : '未处理';
        $data['kindname'] = $data['kind'] ? config('CLIENT_KIND.' . $data['kind']) : '未设置';
        $data['adddate'] = date("Y-m-d H:i", $data['addtime']);
        $data['dealer'] = $data['dealerid'] ? model('AdminUser')->where('userid', $data['dealerid'])->value('realname') : '--';
        $data['brokerid'] = model('AdminUser')->where('userid', $data['brokerid'])->value('realname');
        return $data;
    }
    // protected function getStatusAttr($value, $data) {
    // 	$data['status'] = $data['typeid'] ? config('CLIENT_TYPE.' . $data['typeid']) : '未处理';
    // 	return $data['status'];
    // }

    protected function setTypeidAttr($value, $data)
    {
        if ($value != 2) {
            return $value;
        }
        $info = model('OrderClient')->where('clientid', $data['id'])->where('status', 'in', [0, 5])->field('userid, brokerid, clientid, SUM(totalprice) as price')->find();
        if (!$info['userid']) {
            return $value;
        }
        //经纪人记录
        model('Statistics')->add_log($info['brokerid'], 1, 0, $info['price'], 1, 1);
        //销售总监记录
        model('Statistics')->add_log($info['userid'], 2, 0, $info['price'], 1, 1);
        // 经销商记录
        $dealerid = model('AdminUser')->where('userid', $info['userid'])->value('puserid');
        model('Statistics')->add_log($dealerid, 3, 0, $info['price'], 1, 1);
        // 区域记录
        $quyuid = model('AdminUser')->where('userid', $dealerid)->value('puserid');
        model('Statistics')->add_log($quyuid, 4, 0, $info['price'], 1, 1);
        return $value;
    }

    public function save_datas($data)
    {
        if (!isset($data['name']) || !$data['name']) {
            $this->setError('请输入客户姓名');
            return false;
        }
        if (!isset($data['kind']) || !$data['kind']) {
            $this->setError('请选择线索分类');
            return false;
        }
        if ($data['kind'] == 'gouche' && (!isset($data['cartypeid1']) || !$data['cartypeid1'] || !isset($data['cartypeid2']) || !$data['cartypeid2'])) {
            $this->setError('请选择客户的意向产品');
            return false;
        } else if ($data['kind'] == 'gouche') {
            $carinfo = model('Cartype')->where('id', $data['cartypeid2'])->field('title as product, thumb as carthumb')->find();
            if (isset($carinfo['product'])) {
                $data['product'] = $carinfo['product'];
            }
            if (isset($carinfo['carthumb'])) {
                $data['carthumb'] = $carinfo['carthumb'];
            }
        }
        if (!isset($data['phone']) || !$data['phone']) {
            $this->setError('请输入客户联系方式');
            return false;
        }
        if (isset($data['getdate'])) {
            $data['getdate'] = date('Y-m-d', $data['getdate']);
        }
        $count = $this->where('dealerid', $data['dealerid'])->where('kind', $data['kind'])->where('name', $data['name'])->where('phone', $data['phone'])->where('addtime', '>=', time() - config('CLIENT_VALID_DAYS') * 86400)->count();
        if ($count) {
            $this->setError('此信息已经存在，不能再次提交。');
            return false;
        }
        model('AdminUser')->where('userid', $data['brokerid'])->setField($data['kind'] . 'tag', '1');
        return $this->save_data($data);
    }

    public function update_datas($data)
    {
        if (!isset($data['status']) || $data['status'] < 0) {
            $this->setError('请选择客户状态');
            return false;
        } else if ($data['status'] == 2) {
            // 如果状态是’成交‘
            $data['sucdate'] = date('Y-m-d', time());
            $kind = model('Client')->where('id', $data['id'])->value('kind');
            $userid = model('Client')->where('id', $data['id'])->value('brokerid');
            $viprenew = model('AdminUser')->where('userid', $userid)->value('viprenew');
            if ($viprenew) {
                 // 发放15%的券
                exec_php('/index/cron/send_coupons', ['userid' => $userid, 'clientid' => $data['id'], 'type' => 'baoyang15']);
            } else {
                // 发放10%的券
                exec_php('/index/cron/send_coupons', ['userid' => $userid, 'clientid' => $data['id'], 'type' => $kind]);
            }
            // /************封装模板消息的参数************/
            // // 获取formid
            // // 获取formid
            // $formid = isset($data['formid']) ? $data['formid'] : '';
            // // 获取经销商名称
            // // trace($userid);
            // $openid = model('AdminUser')->where('userid', $userid)->value('openid');
            // $realname = model('AdminUser')->where('userid', $userid)->value('realname');
            // // 线索类型
            // $type = config('CLIENT_KIND');
            // if ($formid != '') {
            // 	$templateMsgData = [
            // 		'openid' => $openid,
            // 		'time' => date("Y-m-d H:i", time()),
            // 		'name' => '线索名称：' . $realname,
            // 		'desc' => '线索类型-' . $type[$kind] . ' 已成交',
            // 		'tip' => '您提报的线索（编号' . $data['id'] . '）已经成交，奖励金近日发放，收到奖励金后，请及时登录小程序，确认',
            // 		'formid' => $formid,
            // 	];
            // 	$wxutils = new WXUtils();
            // 	$wxutils->sendTradeTemplateMsg($templateMsgData);
            // }
        }
        if ($data['kind'] != 'baoyang' && (!isset($data['marketer']) || !$data['marketer'] || $data['marketer'] == '')) {
            $this->setError('请输入销售人员的姓名');
            return false;
        }
        if ($data['kind'] != 'baoyang' && (!isset($data['marketerphone']) || !$data['marketerphone'] || $data['marketer'] == '')) {
            $this->setError('请输入销售人员的电话');
            return false;
        }
        return $this->update_data($data);
    }

    /**
     * 筛选条件
     * @param int $data ['datatype'] all:全部，news:今日新增，suc:今日成交
     * @param int $data ['status'] 0:未处理  1:跟进中 2:成交 3:信息错误 4:失败
     * @param int $data ['kind'] gouche:购车类  xubao:续保类 baoyang:保养类
     * @param int $data ['orderby'] asc:升序  desc:降序
     * @param int $data ['userid'] 成员id
     * @return [type]         [description]
     */
    public function list_datas($data, $uinfo)
    {
        if ($uinfo['roleid'] == 9) {
            $where['brokerid'] = $uinfo['userid'];
        } elseif (in_array($uinfo['roleid'], [7, 8, 10, 11])) {
            $where['dealerid'] = $uinfo['dealerid'];
            switch ($uinfo['roleid']) {
                case 8:
                    $where['kind'] = 'gouche';
                    break;
                case 10:
                    $where['kind'] = 'xubao';
                    break;
                case 11:
                    $where['kind'] = 'baoyang';
                    break;
            }
        } elseif ($uinfo['roleid'] == 5) {
            $dealerids = model('AdminUser')->where('puserid', $uinfo['puserid'])->where('roleid', 6)->column('userid');
            $where['dealerid'] = ['in', $dealerids];
        } else {
            $userids = model('AdminUser')->get_all_childs($uinfo['userid'], $uinfo['roleid'], $uinfo['puserid']);
            $where['userid'] = ['in', $userids];
        }
        if (isset($data['brokerid'])) {
            $where['brokerid'] = $data['brokerid'];
        }
        $page = isset($data['page']) ? $data['page'] : 1;
        $order = 'addtime desc';
        if (isset($data['datatype'])) {
            switch ($data['datatype']) {
                case 'all':
                    break;
                case 'news':
                    $todaystart = strtotime(date('Y-m-d', SYS_TIME) . '00:00:00');
                    $todayend = strtotime(date('Y-m-d', SYS_TIME) . '23:59:59');
                    $where['addtime'] = ['between', [$todaystart, $todayend]];
                    break;
                case 'suc':
                    $todaystart = date('Y-m-d', SYS_TIME);
                    $todayend = date('Y-m-d', SYS_TIME);
                    $where['sucdate'] = ['between', [$todaystart, $todayend]];
                    $where['status'] = '2';
                    break;
            }
        }
        // if (isset($data['city']) && $data['city']) {
        // 	$where['city'] = $data['city'];
        // }
        if (isset($data['status']) && $data['status']) {
            $where['status'] = $data['status'];
        }
        if (isset($data['kind']) && $data['kind']) {
            $where['kind'] = $data['kind'];
        }
        // if (isset($data['source'])) {
        // 	$where['source'] = $data['source'];
        // }
        // if (isset($data['skilled']) && $data['skilled']) {
        // 	// $where['typeid'] = 1;
        // 	$where['skilled'] = $data['skilled'];
        // }
        if (isset($data['orderby']) && $data['orderby']) {
            $order = $data['orderby'] == 'asc' ? "addtime asc" : "addtime desc";
        }
        // if (isset($data['getdate'])) {
        // 	$order = $data['getdate']  == 'asc' ? "getdate asc" : "getdate desc";
        // }
        // if (isset($data['delitime'])) {
        // 	$order = $data['delitime']  == 'asc' ? "delitime asc" : "delitime desc";
        // }
        // if (isset($data['price']) && $data['price']) {
        // 	$order = $data['price'] == 'asc' ? "price asc" : "price desc";
        // }
        $count = $this->where($where)->count();
        trace($where);
        $list = $this->where($where)->order($order)->page($page, 10)->select();
        // $lists = [];
        // foreach ($list as $v){
        // 	$data1[] = $v;
        // }
        return [$count, $list];
    }
}
